package com.kye.express.business.splash;

import com.kye.express.contract.base.BasePresenter;
import com.kye.express.contract.base.view.IView;
import com.kye.model.bean.advertisement.AdvertisementBean;
import com.kye.model.bean.advertisement.AdvertisementType;
import com.kye.model.datasource.AdvertisementDataSource;

import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;

public interface SplashContract {
    interface SplashView extends IView {

        void onADSplashImageUrl(String adImageUrl);
    }

    class SplashPresenter extends BasePresenter<SplashView> {

        private AdvertisementDataSource mAdvertisementDataSource;

        @Override
        public void bind(SplashView view) {
            super.bind(view);
            mAdvertisementDataSource = new AdvertisementDataSource();
        }

        public void getSplashAd() {
            mAdvertisementDataSource.getAdvertisementListForRx(AdvertisementType.TYPE_AD_SPLASH)
                    .filter(new Predicate<List<AdvertisementBean>>() {
                        @Override
                        public boolean test(List<AdvertisementBean> advertisementBeans) throws Exception {
                            return advertisementBeans.size() > 0;
                        }
                    })
                    .map(new Function<List<AdvertisementBean>, AdvertisementBean>() {
                        @Override
                        public AdvertisementBean apply(List<AdvertisementBean> advertisementBeans) throws Exception {
                            return advertisementBeans.get(0);
                        }
                    })
                    .compose(getView().<AdvertisementBean>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<AdvertisementBean>() {
                        @Override
                        public void accept(AdvertisementBean advertisementBean) throws Exception {
                            getView().onADSplashImageUrl(advertisementBean.getSmallImg());
                        }
                    });
        }

        public void getAndSaveAdInfo() {
            mAdvertisementDataSource.getAndSaveAdvertisementList()
                    .compose(getView().<List<AdvertisementBean>>bindToLifecycleDestroy())
                    .subscribe(new Consumer<List<AdvertisementBean>>() {
                        @Override
                        public void accept(List<AdvertisementBean> advertisementBeans) throws Exception {}
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {}
                    });
        }
    }
}
